import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'item/state.dart';
import 'state.dart';

Effect<HomeworkAnswerListState> buildEffect() {
  return combineEffects(<Object, Effect<HomeworkAnswerListState>>{
    Lifecycle.initState: _onReload,
    HomeworkDetailAction.onLoad: _onLoad,
    HomeworkDetailAction.onReload: _onReload,
    HomeworkDetailAction.onDelete: _onDelete,
    HomeworkDetailAction.onMarkAll: _onMarkAll,
    HomeworkDetailAction.onDemand: _onDemand,
  });
}

void _onReload(Action action, Context<HomeworkAnswerListState> ctx) async {
  if (ctx.state.isLoading) {
    return;
  }

  if (action.payload != null) {
    action.payload(); // callback
  }

  _getAnswers(action, ctx, ctx.state.homework.id, GlobalState.firstPageIndex,
      GlobalState.pageSize);
}

void _onLoad(Action action, Context<HomeworkAnswerListState> ctx) async {
  var pageIndex = ctx.state.pageIndex;
  var total = ctx.state.pageTotal;
  var isLoading = ctx.state.isLoading;
  if (pageIndex >= total || isLoading) {
    return;
  }

  _getAnswers(
      action, ctx, ctx.state.homework.id, pageIndex, GlobalState.pageSize);
}

void _onDelete(Action action, Context<HomeworkAnswerListState> ctx) async {
  bool ok = await Util.showConfirmDialog('删除', '确定要删除？', ctx.context);
  if (!ok) {
    return;
  }

  ctx.dispatch(HomeworkDetailActionCreator.loading());
  int index = action.payload;
  var item = ctx.state.items[index];
  var url = "/correct/pub/api/exercises/del.mvc";
  final query = {'id': item.id};
  var result = await Http.get(url, query: query);

  ctx.dispatch(HomeworkDetailActionCreator.loaded());
  if (result.success) {
    ctx.dispatch(HomeworkDetailActionCreator.deleted(index));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _onDemand(Action action, Context<HomeworkAnswerListState> ctx) async {
  Navigator.of(ctx.context)
      .pushNamed(Nav.DEMAND, arguments: ctx.state.homework);
}

void _onMarkAll(Action action, Context<HomeworkAnswerListState> ctx) async {
  ctx.dispatch(HomeworkDetailActionCreator.loading());
  int index = action.payload;
  var url = "/correct/teacher/api/batch/review.mvc";
  final query = {'id': ctx.state.homework.id};
  var result = await Http.get(url, query: query);

  ctx.dispatch(HomeworkDetailActionCreator.loaded());
  if (result.success) {
    Util.alert('一键批阅成功', ctx.context);
    ctx.dispatch(HomeworkDetailActionCreator.onReload(null));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _getAnswers(Action action, Context<HomeworkAnswerListState> ctx, String id,
    int pageIndex, int pageSize) async {
  ctx.dispatch(HomeworkDetailActionCreator.loading());

  var url = "/correct/teacher/api/homework/detail.mvc";
  final query = {'id': id, 'cpage': pageIndex, 'psize': pageSize};
  var result = await Http.get(url, query: query);

  ctx.dispatch(HomeworkDetailActionCreator.loaded());
  if (result.success) {
    var responseList = result.data['studentHomeworkList'];
    var pageTotal = 0; // 没有分页

    pageIndex += 1;
    List<HomeworkAnswerState> items = new List();
    if (responseList != null) {
      responseList.forEach((item) {
        try {
          HomeworkAnswerState cellData = new HomeworkAnswerState.fromJson(item);
          items.add(cellData);
        } catch (e) {
          // No specified type, handles all
        }
      });
    }

    ctx.dispatch(
        HomeworkDetailActionCreator.listResult(items, pageTotal, pageIndex));
  } else {
    Util.alertFail(result, ctx.context);
  }
}
